<style scoped lang="scss">
$white-color: #fff; // 补充变量定义（原代码未显示，避免报错）

.calendar-picker {
  width: 10rem;
  height: 14.7733rem;
  background-color: $white-color;
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 999;
  border-radius: 0.2667rem 0.2667rem 0 0;

  .calendar-picker-header {
    width: 10rem;
    height: 3.1467rem;
    background-color: $white-color;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: space-around;

    .calendar-picker-header-title {
      font-size: 0.48rem;
      color: #000;
    }

    .calendar-picker-header-center {
      font-size: 0.48rem;
      color: #000;
    }

    .calendar-picker-header-buttom {
      width: 10rem;
      height: 1.0667rem;
      border-bottom: 1px solid #000;
      box-sizing: border-box;

      ul {
        width: 10rem;
        height: 1.0667rem;
        display: flex;
        align-items: center;
        justify-content: space-around;
        margin: 0;
        padding: 0;
        list-style: none;

        li {
          font-size: 0.4267rem;
          color: #000;
        }
      }
    }
  }

  .calendar-picker-content {
    width: 10rem;
    height: 8.1867rem;
    background-color: $white-color;
    overflow: auto;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    @include horizontal-scroll-hidden;
    margin-top: 0.4rem;

    .box {
      width: 10rem;
      height: 8.1867rem;
    }

    .calendar-picker-content-bottom {
      width: 10rem;
      height: .96rem;
    }

    .calendar-picker-content-title {
      width: 10rem;
      height: 1.0667rem;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 0.4267rem;
      color: #000;
    }

    .calendar-picker-content-top {
      width: 10rem;
      height: 6.5867rem;
      margin-top: 0.2667rem;

      ul {
        width: 10rem;
        height: 1.0667rem;
        margin: 0;
        padding: 0;
        list-style: none; // 清除默认列表样式

        li {
          width: 1.42rem;
          height: 1.44rem;
          float: left;
          font-size: 0.4267rem;
          color: #000;
          display: flex;
          align-items: center;
          justify-content: center;
          border-radius: 0.1rem;
          cursor: pointer;
          box-sizing: border-box;

          // 非当前月日期样式（灰色、不可点击）
          &.non-current-month {
            color: #ccc;
            cursor: not-allowed;
          }

          // 选中日期样式（红色背景、白色文字）
          &.selected-date {
            background-color: #ee0a24;
            color: $white-color;
          }

          // 今日日期样式（红色边框）
          &.today-date {
            border: 1px solid #ee0a24;
          }
        }
      }
    }
  }
}

.calendar-picker-content-bottom {
  width: 10rem;
  height: 1.0667rem;
  background-color: $white-color;
  position: absolute;
  bottom: 1rem;
  left: 0;

  button {
    width: 9rem;
    background-color: #ee0a24;
    height: 1.0667rem;
    font-size: 0.4267rem;
    border: 0;
    border-radius: 1rem;
    margin-left: 0.5rem;
    color: $white-color;
    cursor: pointer;

    // 按钮禁用样式
    &:disabled {
      background-color: #ccc;
      cursor: not-allowed;
    }
  }
}
</style>

<template>
  <!-- 日历选择器 -->
  <div class="calendar-picker">
    <div class="calendar-picker-header">
      <div class="calendar-picker-header-title">
        <span>日期选择</span>
      </div>
      <div class="calendar-picker-header-center">
        <span>{{ currentYear }}年{{ currentMonth + 1 }}月</span>
      </div>
      <div class="calendar-picker-header-buttom">
        <ul>
          <li>日</li>
          <li>一</li>
          <li>二</li>
          <li>三</li>
          <li>四</li>
          <li>五</li>
          <li>六</li>
        </ul>
      </div>
    </div>

    <!-- 日历内容（滚动时同步更新头部月份） -->
    <div class="calendar-picker-content" ref="content" @scroll="handleScroll">
      <div class="box" ref="box">
        <div v-for="(monthData, index) in allMonthsData" :key="index">
          <div class="calendar-picker-content-title">
            <p>{{ monthData.year }}年{{ monthData.month + 1 }}月</p>
          </div>
          <div class="calendar-picker-content-top">
            <!-- 按周拆分日期（修复原代码日期一行显示问题） -->
            <ul v-for="(week, weekIndex) in monthData.weeks" :key="weekIndex">
              <li v-for="(date, dateIndex) in week" :key="dateIndex" :class="{
                'non-current-month': !date.isCurrentMonth,
                'selected-date': selectedDate && selectedDate.date?.getTime() === date.date?.getTime(),
                'today-date': date.isToday && date.isCurrentMonth
              }" @click="handleDateClick(date)">
                {{ date.day }}
              </li>
            </ul>
          </div>
        </div>
      </div>
    </div>

    <!-- 确认按钮（未选中时禁用） -->
    <div class="calendar-picker-content-bottom">
      <button @click="handleConfirm" :disabled="!selectedDate">确认</button>
    </div>
  </div>
</template>

<script>
export default {
  name: 'CalendarPicker',
  data() {
    return {
      startY: 0,
      allMonthsData: [], // 存储所有月份的日历数据（按周拆分）
      currentYear: new Date().getFullYear(), // 头部显示的当前年份
      currentMonth: new Date().getMonth(), // 头部显示的当前月份（0-11）
      startYear: 2020, // 起始年份（可自定义）
      selectedDate: null // 选中的日期对象
    }
  },
  mounted() {
    // 初始化日历数据
    this.generateAllMonthsCalendar();
    // DOM更新后滚动到当前月份
    this.$nextTick(() => {
      this.initScrollToCurrentMonth();
    });
  },
  beforeDestroy() {
    // 移除滚动事件监听（避免内存泄漏）
    const contentEl = this.$refs.content;
    if (contentEl) {
      contentEl.removeEventListener('scroll', this.handleScroll);
    }
  },
  methods: {
    // 判断是否为今日
    isToday(date) {
      const today = new Date();
      return date.getFullYear() === today.getFullYear() &&
        date.getMonth() === today.getMonth() &&
        date.getDate() === today.getDate();
    },

    // 生成所有月份的日历数据（按周拆分）
    generateAllMonthsCalendar() {
      const now = new Date();
      const currentYear = now.getFullYear();
      const currentMonth = now.getMonth();
      const allMonthsData = [];

      // 遍历起始年到当前年
      for (let year = this.startYear; year <= currentYear; year++) {
        // 当前年只生成到本月，其他年生成全年
        const endMonth = year === currentYear ? currentMonth + 1 : 12;

        for (let month = 0; month < endMonth; month++) {
          const firstDay = new Date(year, month, 1); // 当月第一天
          const lastDay = new Date(year, month + 1, 0); // 当月最后一天
          const firstDayOfWeek = firstDay.getDay(); // 当月第一天是周几（0=周日）
          const daysInMonth = lastDay.getDate(); // 当月总天数

          const monthDays = [];

          // 1. 填充当月第一天之前的空白（上月剩余日期）
          for (let i = 0; i < firstDayOfWeek; i++) {
            monthDays.push({
              day: '',
              isCurrentMonth: false,
              isToday: false,
              date: null
            });
          }

          // 2. 填充当月日期
          for (let i = 1; i <= daysInMonth; i++) {
            const date = new Date(year, month, i);
            monthDays.push({
              day: i,
              isCurrentMonth: true,
              isToday: this.isToday(date),
              date: date
            });
          }

          // 3. 按周拆分（每7天一组，确保日历按周换行）
          const weeks = [];
          let tempWeek = [];
          for (const day of monthDays) {
            tempWeek.push(day);
            if (tempWeek.length === 7) {
              weeks.push(tempWeek);
              tempWeek = [];
            }
          }
          // 补全最后一周（不足7天的情况）
          if (tempWeek.length > 0) {
            const fillCount = 7 - tempWeek.length;
            for (let i = 0; i < fillCount; i++) {
              tempWeek.push({ day: '', isCurrentMonth: false, isToday: false, date: null });
            }
            weeks.push(tempWeek);
          }

          // 4. 保存当月数据
          allMonthsData.push({
            year: year,
            month: month,
            weeks: weeks // 存储按周拆分的日期
          });
        }
      }

      // 反转数组：最新月份显示在顶部
      this.allMonthsData = allMonthsData.reverse();
    },

    // 日期点击事件（仅当前月日期可选中）
    handleDateClick(date) {
      if (date.isCurrentMonth && date.date) {
        this.selectedDate = date;
      }
    },

    // 确认按钮事件（触发父组件回调）
    handleConfirm() {
      if (this.selectedDate?.date) {
        // 格式化日期为 "YYYY-MM-DD"（方便父组件使用）
        const formattedDate = this.formatDate(this.selectedDate.date);
        // 触发自定义事件，传递选中的日期信息
        this.$emit('confirm', {
          originalDate: this.selectedDate.date, // 原始Date对象
          formattedDate: formattedDate // 格式化后的字符串
        });
        // 可根据需求添加关闭日历的逻辑（如触发close事件）
        // this.$emit('close');
      }
    },

    // 日期格式化工具
    formatDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 滚动事件：同步头部显示的当前月份
    handleScroll() {
      const contentEl = this.$refs.content;
      if (!contentEl || this.allMonthsData.length === 0) return;

      // 每个月份块的高度（标题1.0667rem + 内容6.5867rem）
      const monthHeight = 1.0667 + 6.5867;
      // 当前滚动距离
      const scrollTop = contentEl.scrollTop;
      // 计算当前视图对应的月份索引
      const currentIndex = Math.round(scrollTop / monthHeight);
      const validIndex = Math.max(0, Math.min(currentIndex, this.allMonthsData.length - 1));
      // 更新头部年月
      const currentMonthData = this.allMonthsData[validIndex];
      this.currentYear = currentMonthData.year;
      this.currentMonth = currentMonthData.month;
    },

    // 初始化滚动到当前月份
    initScrollToCurrentMonth() {
      const contentEl = this.$refs.content;
      if (!contentEl || this.allMonthsData.length === 0) return;

      // 当前月份在数组中索引为0（allMonthsData已反转）
      const currentMonthIndex = 0;
      const monthHeight = 1.0667 + 6.5867;
      // 滚动到当前月份顶部
      contentEl.scrollTop = currentMonthIndex * monthHeight;
    }
  }
}
</script>